// package-star/pages/brand-open/index.js
const app = getApp();
import { TARGET_TYPE } from '../../../constants/common';
import { TAB_BAR_PAGE } from '../../../constants/route';
import { reLaunchTo, tipToast, showLoading, hideLoading, tipSuccess } from '../../../common/env';
import { setMangeTargetId } from '../../../biztools/wex';
import { openBrand } from '../../../api/brd';

Page({
    mixins: [],
    data: {
        brandInfo: {},
    },
    onLoad(options) {
        const { remotePkOfBrand } = options;
        remotePkOfBrand && app.event.addListener('sendPreBrandInfo', this._handleGetPreBrandInfo.bind(this));
    },
    onUnload() {
        app.event.removeListener('sendPreBrandInfo');
    },
    _handleGetPreBrandInfo(brandInfo) {
        this.setData({ brandInfo });
    },
    handleChange(e) {
        const { type } = e.currentTarget.dataset;
        const { brandInfo } = this.data;
        const value = type === 'pic' ? e.detail : e.detail.value;
        brandInfo[type] = value;
        this.setData({ brandInfo });
    },
    async handleCreate() {
        const { brandInfo } = this.data;
        const { pic, name } = brandInfo;
        if (!pic) {
            tipToast('请上传品牌LOGO');
            return;
        }
        if (!name) {
            tipToast('请输入品牌名称');
            return;
        }
        showLoading('保存中...');
        const flag = await openBrand(brandInfo);
        if (flag) {
            hideLoading();
            tipSuccess('创建成功');
            setMangeTargetId(TARGET_TYPE.brand, flag.brandId);
            reLaunchTo(TAB_BAR_PAGE['star']);
        }
    },
})
